package com.skillworld.webapp.model.course;

import java.util.List;
import java.util.Locale;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.skillworld.webapp.model.course.Course.Status;
import com.skillworld.webapp.model.util.dao.GenericDaoHibernate;


@Repository("CourseDao")
public class CourseDaoHibernate 
        extends GenericDaoHibernate<Course,Long> 
        implements CourseDao
{
    private Criteria buildSearch(List<String> keywords, 
            Long dept, Locale locale, Long author,
            Status status)
    {
        Criteria q = getSession().createCriteria(Course.class);

        for (String k : keywords)
        {
            Criterion inName = Restrictions.ilike("name", k, MatchMode.ANYWHERE);
            Criterion inDescr = Restrictions.ilike("description", k, MatchMode.ANYWHERE);
            q.add(Restrictions.or(inName, inDescr));
        }

        if (dept != null)
        { q.add(Restrictions.eq("department.departmentId", dept)); }

        if (locale != null)
        { q.add(Restrictions.le("locale", locale)); }

        if (author != null)
        { q.add(Restrictions.eq("author.userId", author)); }
        
        if (status != null)
        { q.add(Restrictions.eq("status", status)); }

        return q;
    }
    
    @SuppressWarnings("unchecked")
    public List<Course> search(List<String> keywords, Long dept, Locale locale,
            Long author, Status status, int startIndex, int count) 
    {
        return(List<Course>) 
            buildSearch(keywords, dept, locale, author, status)
                .addOrder(Order.asc("name"))
                .setFirstResult(startIndex)
                .setMaxResults(count)
                .list();
    }

    public long numberOfCourses(List<String> keywords, Long dept,
            Locale locale, Long author, Status status) 
    {
        return(Long) buildSearch(keywords, dept, locale, author, status)
                        .setProjection(Projections.rowCount())
                        .uniqueResult();
    }
}
